import { sys } from "cc";

export default class LocalStorage {
    static setBoolean(_key: string, _value: boolean) {
        sys.localStorage.setItem(_key, _value.toString())
    }

    static getBoolean(_key: string, def?: boolean): boolean {
        if (!def) {
            def = false
        }
        let ret = <string> sys.localStorage.getItem(_key)
        if (ret == null || ret.length == 0) return def
        if (ret == "true") return true
        else return false
    }

    static setInt(_key: string, _value: number) {
        sys.localStorage.setItem(_key, Math.round(_value).toString())
    }

    static getInt(_key: string, def?: number): number {
        if (!def) {
            def = 0
        }
        let ret = <string> sys.localStorage.getItem(_key)
        if (ret == null || ret.length == 0) return Math.round(def)
        return parseInt(ret)
    }

    static setFloat(_key: string, _value: number) {
        sys.localStorage.setItem(_key, _value.toString())
    }

    static getFloat(_key: string, def?: number): number {
        if (!def) {
            def = 0
        }
        let ret = <string> sys.localStorage.getItem(_key)
        if (ret == null || ret.length == 0) return def
        return parseFloat(ret)
    }

    static async setString(_key: string, _value: string) {
        sys.localStorage.setItem(_key, _value)
    }

    static getString(_key: string, def?: string): string {
        if (!def) {
            def = ""
        }
        let ret = <string> sys.localStorage.getItem(_key)
        if (!ret || ret.length == 0) return def
        return ret
    }

    static async setObj<T>(_key: string, _value: T) {
        if (!_value) {
            sys.localStorage.setItem(_key, "{}")
            return
        }
        this.setString(_key, JSON.stringify(_value))
    }

    /**
     * 传入default, 会生成T的完整实例,而不是一个兼容的json对象.
     * @param {string} _key
     * @param {T} def
     * @returns {T}
     */
    static getObj<T>(_key: string, def?: T): T {
        let ret = <string> sys.localStorage.getItem(_key)
        if (!ret || ret.length == 0) return def
        else if (def) {
            return Object.assign(def, JSON.parse(ret))
        } else {
            return JSON.parse(ret) as T
        }
    }

    static remove(_key: string) {
        sys.localStorage.removeItem(_key)
    }
}
